/* Cobber create 2024/04/14 */

const amqplib = require('amqplib/callback_api');
const { RABBIT_HOST, RABBIT_EX, RABBIT_QUEUE } = require('../config/rabbit.config')

const start = (host, queue) => {
  amqplib.connect(host, (err, conn) => {
    if (err) {
      console.error('Could not connect to RabbitMQ', err)
      return
    }
    conn.createChannel((err, ch) => {
      if (err) {
        console.error('Could not create channel', err)
        return
      }
      ch.assertQueue(queue, { durable: true }, (err, q) => {
        if (err) {
          console.error('Could not assert queue', err)
          return
        }
        console.log('Waiting for messages in %s. To exit press CTRL+C', queue)
        ch.prefetch(4)
        ch.consume(queue, (msg) => {
          if (Array.isArray(msg)) {
            msg.forEach(m => {
              const payload = m.content.toString()
              console.log('Received message', payload.includes('{') ? JSON.parse(payload) : payload)
              ch.ack(m)
            })
          } else {
            const payload = msg.content.toString()
            console.log('Received message', payload.includes('{') ? JSON.parse(payload) : payload)
            ch.ack(msg)
          }
        }, { noAck: false })
      })
    })
    conn.on('error', (err) => {
      console.error('RabbitMQ connection error', err)
      start(host)
    })
  })
}

start(RABBIT_HOST, RABBIT_QUEUE)